import axios from 'axios'
import store from '@/store/index.js'
import JSONbig from 'json-bigint'
import router from '../router'

const http = axios.create({
  baseURL: 'https://www.kungfubuy.com',
  transformResponse: [function (data) {
    try {
      return JSONbig.parse(data)
    } catch (err) {
      return data
    }
  }]

})

http.interceptors.request.use(function (config) {
  const token = store.state.tokenInfo.token
  // console.log(token)
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function (err) {
  return Promise.reject(err)
})

// 添加响应拦截器
http.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, async function (error) {
  // 对响应错误做点什么
  console.dir(error)
  if (error.response.status === 401) {
    // console.log('出错了')
    const refreshToken = store.state.tokenInfo.refresh_token
    // console.log(refreshToken)
    if (refreshToken) {
      try {
        console.log('存在refreshToken')
        const res = await axios({
          method: 'put',
          url: 'http://ttapi.research.itcast.cn/app/v1_0/authorizations',
          // 请求头中携带refresh_token信息
          headers: {
            Authorization: `Bearer ${refreshToken}`
          }
        })
        // console.log(res)
        const newToken = res.data.data.token
        store.commit('setTokenInfo', {
          token: newToken,
          refresh_token: refreshToken

        })
        return http(error.config)
      } catch {
        store.commit('removeToken')
        console.dir(router)
        router.push({
          path: 'login',
          query: {
            backto: router.currentRoute.fullPath
          }
        })
      }
    } else {
      console.log('不存在refreshToken')
      store.commit('removeToken')
      console.dir(router)
      router.push({
        path: '/login',
        query: {
          backto: router.currentRoute.fullPath
        }
      })
    }
  }
  return Promise.reject(error)
})
export default http
